package com.yunkeji.admin.controller.broker;

import cn.dev33.satoken.annotation.SaIgnore;
import com.yunkeji.common.constant.Constants;
import com.yunkeji.common.core.domain.R;
import com.yunkeji.common.core.domain.model.LoginBody;
import com.yunkeji.common.core.domain.model.LoginUser;
import com.yunkeji.common.helper.LoginHelper;
import com.yunkeji.dao.domain.broker.BrokerMenu;
import com.yunkeji.dao.domain.broker.BrokerUser;
import com.yunkeji.dao.vo.RouterVo;
import com.yunkeji.system.service.BrokerLoginService;
import com.yunkeji.system.service.IBrokerMenuService;
import com.yunkeji.system.service.IBrokerUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 推广系统登录验证
 *
 * @author 雷擎宇
 */
@Validated
@RequiredArgsConstructor
@RestController
public class BrokerLoginController {

    private final BrokerLoginService loginService;
    private final IBrokerMenuService menuService;
    private final IBrokerUserService userService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/loginBroker")
    public R<Map<String, Object>> login(@Validated @RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token =
                loginService.login(
                        loginBody.getUsername(),
                        loginBody.getPassword(),
                        loginBody.getCode(),
                        loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }

    /** 退出登录 */
    @SaIgnore
    @PostMapping("/logoutBroker")
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfoBroker")
    public R<Map<String, Object>> getInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        BrokerUser user = userService.selectUserById(loginUser.getUserId());
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("permissions", loginUser.getMenuPermission());
        return R.ok(ajax);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRoutersBroker")
    public R<List<RouterVo>> getRouters() {
        Long userId = LoginHelper.getUserId();
        List<BrokerMenu> menus = menuService.selectMenuList(userId);
        return R.ok(menuService.buildMenus(menus));
    }
}
